<style>
    .layui-form-item .layui-inline {
        margin-top: 10px;
    }
</style>
<div class="layui-fluid" id="Ship-create">
    <div class="layui-card">
        <div class="layui-form" lay-filter="LAY-list-form">
            <div id="view"></div>
        </div>
    </div>
</div>
<script id="page1" type="text/html">
    <input type="hidden" name="id" value="{{layui.router().search.id||''}}">
    <div class="layui-card-header">配送计划资料</div>
    <div class="layui-card-body">
        <div class="layui-form-item">
            {{# if(layui.router().search.id>0){ }}
            <div class="layui-inline">
                <label class="layui-form-label">配送计划号</label>
                <div class="layui-input-inline">
                    <span class="layui-input layui-input-none">{{d.plan.code||''}}</span>
                </div>
            </div>
            {{# } }}
            <div class="layui-inline">
                <label class="layui-form-label">*国家</label>
                <div class="layui-input-inline">
                    <select lay-filter="country_id_rec" name="country_id_rec" id="country_id_rec" lay-verify="required" lay-search>
                        <option value="">请选择</option>
                        {{# for(var i in d.info.country){ if(i==d.plan.country_id_rec){ var
                        selected='selected';}else{ var selected=''; } }}
                        <option value="{{i}}" {{selected}}>{{d.info.country[i]}}</option>
                        {{# } }}
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">*发运公司</label>
                <div class="layui-input-inline layui-jy-width200">
                <select lay-filter="company_id_out" id="company_id_out" name="company_id_out" lay-verify="required" lay-search>
                    <option value="">请选择发运公司</option>
                </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">*发货仓库</label>
                <div class="layui-input-inline">
                    <select lay-filter="warehouse_id_out" name="warehouse_id_out" id="warehouse_id_out" lay-verify="required" lay-search>
                        <option value="">请选择发货仓库</option>
                        {{# for(var i in d.info.countryWarehouse){ if(i==d.plan.warehouse_id_out){ var
                        selected='selected';}else{ var selected=''; } }}
                        <option value="{{i}}" {{selected}}>{{d.info.countryWarehouse[i]}}</option>
                        {{# } }}
                    </select>
                </div>
            </div>
             <div class="layui-inline">
                <label class="layui-form-label layui-label-jy">*收货公司</label>
                <div class="layui-input-inline">
                    <select name="recieve_company" id="recieve_company" lay-filter="recieve_company" lay-verify="required" lay-search >
                        <option value="">请选择</option>
                        {{# for(var i in d.info.lsCompany){ if(i==d.plan.recieve_company){ var selected='selected';}else{
                        var selected=''; } }}
                        <option value="{{i}}" {{selected}}>{{d.info.lsCompany[i]}}</option>
                        {{# } }}
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">*收货店铺</label>
                <div class="layui-input-inline">
                    <select lay-filter="shop_id_rec" name="shop_id_rec" id="shop_id_rec" lay-verify="required" lay-search>
                        <option value="">请选择</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">*收货仓库</label>
                <div class="layui-input-inline">
                    <input id="warehouse_id_rec" lay-verify="required"  name="warehouse_id_rec" value="{{d.plan.warehouse_id_rec||''}}"
                           type="hidden">
                    <span id="warehouse_str_rec"
                          class="layui-input layui-input-none">{{d.plan.warehouse_str_rec||''}}</span>
                </div>
            </div>


            <div class="layui-inline">
                <label class="layui-form-label layui-label-jy">*配送类型</label>
                <div class="layui-input-inline">
                    <select name="type" lay-search lay-verify="required" id="type">
                        <option value="">请选择</option>
                        <option value="1" {{ d.plan.type == 1 ? 'selected' : '' }}>调拨</option>
                        <option value="2" {{ d.plan.type == 2 ? 'selected' : '' }}>采销</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label  layui-label-jy">*需求配送时间</label>
                <div class="layui-input-inline">
                    <input type="text" name="distribution_time" class="layui-input" id="fy1Time" placeholder="yyyy-MM-dd"
                           lay-verify="required">
                </div>
            </div>
            
            {{# if(layui.router().search.type>0){}}
            <div class="layui-inline">
                <label class="layui-form-label">创建人</label>
                <div class="layui-input-inline">
                    <span class="layui-input layui-input-none">{{d.plan.operator||''}}</span>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">创建时间</label>
                <div class="layui-input-inline">
                    <span class="layui-input layui-input-none">{{d.plan.ctime||''}}</span>
                </div>
            </div>
            {{# } }}
        </div>
    </div>

    <div class="layui-card-header">商品信息</div>
    <div class="layui-card-body">
        <div class="layui-tab">
            <div class="layui-tab-content">
                <div class="tab1 layui-tab-item layui-show">
                    <div class="layui-item">
                        {{# if(d.plan.status==0  || !layui.router().search.id) { }}
                        <button class="uploadPage layui-btn">导入</button>
                        <button class="add layui-btn">新增</button>
                        {{#} }}
                       <!-- <button class="export1 layui-btn">导出</button>-->
                    </div>
                    <table id="LAY-list" lay-filter="LAY-list"></table>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-card-body layui-jy-center">
        <a lay-href="Distribution/index" class="layui-btn">返回</a>
        {{# if(d.plan.status==0 ||!layui.router().search.id) { }}
        <input type="button" lay-submit lay-filter="LAY-submit-1" value="保存" class="layui-btn LAY-submit1">
        {{#} }}
    </div>

</script>
<!-- 行内工具 -->
<script type="text/html" id="LAY-list-toolbar">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="del" href="javascript:;">删除</a>
</script>
<script>
    layui.use(['admin', 'form', 'toolJ', 'laytpl', 'laydate', 'upload', 'table','multiSelect'], function () {
        var $ = layui.$
            , form = layui.form
            , laytpl = layui.laytpl
            , setter = layui.setter
            , laydate = layui.laydate
            , table = layui.table
            , toolJ = layui.toolJ;
        var id = layui.router().search.id;
        var type = layui.router().search.type;
        //新增
        $('#Ship-create').off('click.add').on('click.add', '.add', function () {
            table.cache["LAY-list"].unshift({
                "sku": "",
                "sku_name": "",
                "available_stock": "",
                "quantity": 0,
                "price": 0
            });
            tableView(table.cache["LAY-list"]);
        });
        //监听上传按钮
        $('#Ship-create').off('click.uploadPage').on('click.uploadPage', '.uploadPage', function () {
            var warehouse_id=$("#warehouse_id_out").val();
            if (typeof layui.table.cache['LAY-list'] != 'undefined' && table.cache['LAY-list'].length > 0) {
                layer.confirm('已存在数据,重新导入会将之前导入的清空是否确定!', function () {   
                    upload(warehouse_id);
                });
            } else {
                upload(warehouse_id);
            }
        });
        //选国家自动带出公司
        form.on('select(country_id_rec)', function (d) {
        //    debugger;
            //选国家自动带出公司
            showCompany(d.value);
        });
        
        form.on('select(company_id_out)', function (d) {
        //    debugger;
            showShopWarehouse(d.value,'1');  
        });
        form.on('select(recieve_company)', function (d) {
        //    debugger;
            showShopWarehouse(d.value,'2');
        });
        form.on('select(shop_id_rec)', function (d) {
            toolJ.ajax({"data": {'shop_id':d.value},'url':"/index/Distribution/getWarehouseByShopId"},function(data){  
                var type=1;
                if(Object.keys(data.data).length>0){
                    $("#warehouse_id_rec").val(data.data.id); 
                    $("#warehouse_str_rec").text(data.data.warehouse_name);
                    if(data.data.type==4){
                        type=2;
                    }
                }else{
                    $("#warehouse_id_rec").val(''); 
                    $("#warehouse_str_rec").text('');
                }
                $("#type").val(type); 
               form.render(null, 'LAY-list-form'); 
           });
        });
        //获取发货仓库、收货店铺信息
        function showShopWarehouse(base_company_id='',type='1',default_value=''){
            if(type==1){//发货
               var type=1;
               var html="<option value=''>请选择发货仓库</option>"; 
            }else{//收货
               var type=2;
                var html="<option value=''>请选择收货店铺</option>";
            }
            if(base_company_id=='' && type==1){
                $("#warehouse_id_out").html(html); 
                form.render(null, 'LAY-list-form');
            }else if(base_company_id=='' && type==2){
                $("#warehouse_id_rec").html(html); 
                form.render(null, 'LAY-list-form');
            }
            toolJ.ajax({"data": {'base_company_id':base_company_id},'url':"/index/Distribution/getShopWarehouse?type="+type},function(data){     
               if(Object.keys(data.data).length>0){
                   for(var i in data.data){
                       if(default_value.warehouse_id_out==i && type==1){
                            html+="<option value='"+i+"' selected>"+data.data[i]+"</option>";
                        }else if(default_value.shop_id_rec==i && type==2){
                            html+="<option value='"+i+"' selected>"+data.data[i]+"</option>";
                        }else {
                             html+="<option value='"+i+"'>"+data.data[i]+"</option>";
                        }
                   }
               } 
               if(type==1){
                  $("#warehouse_id_out").html(html); 
               }else{
                  $("#shop_id_rec").html(html); 
               }
               form.render(null, 'LAY-list-form'); 
           });
        };
        //获取发运公司、收货公司信息
        function showCompany(selectedValue='',default_value=''){
           // debugger;
            var html="<option value=''>请选择发运公司</option>"; 
            var html1="<option value=''>请选择收货公司</option>";
            if(selectedValue=='' && type==1){
                $("#company_id_out").html(html);
                form.render(null, 'LAY-list-form');
            }else if(selectedValue=='' && type==2){
                $("#recieve_company").html(html1);
                form.render(null, 'LAY-list-form');
            }
             if (selectedValue) {
                toolJ.ajax({"data": {'country_id':selectedValue,'type':1},'url':"/index/Distribution/getCompany"},function(data){
                     html="<option value=''>请选择发运公司</option>"; html1="<option value=''>请选择收货公司</option>";
                     select_data='';select_data1='';
                    if(Object.keys(data.data['1']).length>0){
                        for(var i in data.data['1']){
                            if(default_value.company_id_out==i){
                                html+="<option value='"+i+"' selected>"+data.data['1'][i]+"</option>";
                            }else{
                                html+="<option value='"+i+"'>"+data.data['1'][i]+"</option>";
                            }
                        }
                    } 
                    $("#company_id_out").html(html);
                    form.render(null, 'LAY-list-form');
                    if(Object.keys(data.data['2']).length>0){
                        for(var i in data.data['2']){
                            if(default_value.recieve_company==i){
                                html1+="<option value='"+i+"' selected>"+data.data['2'][i]+"</option>";
                            }else{
                                html1+="<option value='"+i+"'>"+data.data['2'][i]+"</option>";
                            }
                        }
                    }
                    $("#recieve_company").html(html1);
                    form.render(null, 'LAY-list-form');  
                });
            } 
        }
        //导出
        $("body").off('click.export1').on('click.export1', '.export1', function () {
            $(".layui-inline[lay-event='LAYTABLE_EXPORT']").click();
            $(".tab1 li[data-type='csv']").click();
        })

        function tableView(data) {
            var url = '';
            var jdata = '';
            if (data.length > 0) {
                jdata = data;
            } else {
                url = 'index/Distribution/detailTemp';
                //jdata={};
            }
            table.render({
                elem: '#LAY-list'
                , url: url
                , data: jdata
                , cellMinWidth: 80
                , cols: [[
                     {field: 'sku', title: 'sku', edit: 'text'}
                    , {field: 'sku_name', title: '采购名称'}
                    , {field: 'quantity', title: '数量', edit: 'text'}
                    , {field: 'available_stock', title: '可用库存'}
                    , {field: 'price', title: '参考价（¥）'}
                    , {title: '操作', width: 70, align: 'center', fixed: 'right', toolbar: '#LAY-list-toolbar'}
                ]]
                , page: false
                , limit: 100000
                ,text:{none: '暂无相关数据!' }
            });
        }


        function upload(warehouseid) {
            //第一个链接为上传api 第二个链接是模板下载链接 第三个是成功回调
            toolJ.upload('/index/Distribution/upload?warehouse_id='+warehouseid, '/attachment/importcvs/distribution_detail.csv', function (res) {
                if (res.code == 1) {
                    tableView(res.data);
                }
            });
        }

        function viewHtml(data) {
            var getTpl = page1.innerHTML
                , view = $('#view');
            laytpl(getTpl).render(data, function (html) {
                view.html(html);
            });
            laydate.render({
                elem: '#fy1Time'
                , value: data.plan.distribution_time ? data.plan.distribution_time : ''
            });
           tableView(data.detail);

            table.render(null, 'LAY-list');
            form.render(null, 'LAY-list-form');
            //监听提交
            form.on('submit(LAY-submit-1)', function (data) {
                if (typeof table.cache['LAY-list'] != 'undefined' && table.cache['LAY-list'].length > 0) {
                    data.field.list = JSON.stringify(table.cache['LAY-list']);
                    var list=table.cache['LAY-list'];
                    for(var i in list){
                        if(list[i]['sku']=='' || list[i]['sku_name:']=='' || list[i]['quantity']==0){
                            toolJ.error('sku或产品名称或计划数量格式不正确');
                            return false;
                        } 
                        if(list[i]['available_stock']==0){
                            toolJ.error('sku的可用库存不能为0');
                            return false;
                        }
                    }
                    if(data.field.warehouse_id_out==data.field.warehouse_id_rec){
                         toolJ.error('发货仓库和收货仓库不能相同');
                         return false;
                    }
                    console.log(data);
                    toolJ.ajax({"data": data.field});
                } else {
                    toolJ.error('不存在明细!');
                }
            });
            //监听行内操作
            table.on('tool(LAY-list)', function (obj) {
                switch (obj.event) {
                    case 'del':
                        layer.confirm('确定删除这条数据吗？', function (index) {
                            obj.del();
                            layer.close(index);
                        });
                        break;
                }
            });
            var country_id_rec=data.plan.country_id_rec;
            var company_id_out=data.plan.company_id_out;
            var recieve_company=data.plan.recieve_company;
            showCompany(country_id_rec,data.plan);
            showShopWarehouse(company_id_out,1,data.plan);
            showShopWarehouse(recieve_company,2,data.plan);
        }

        var info = {};
        info.shop = layui.data(setter.tableName).shop;
        info.warehouse = layui.data(setter.tableName).warehouse;
        info.company = layui.data(setter.tableName).company;
        info.country = layui.data(setter.tableName).country;
        info.warehouseCountry = layui.data(setter.tableName).warehouseCountry;
        if (id) {
            toolJ.ajax({"data": {"id": id}, "type": "get"},
                function (data) {
                    info.myCompany=data.data.myCompany;
                    info.lsCompany=data.data.lsCompany;
                    info.countryWarehouse=data.data.countryWarehouse;
                    viewHtml({"info": info, "plan": data.data.plan, "type": 1, "detail": data.data.detail});
                }
            );
        } else {
            toolJ.ajax({"data": {}, "type": "get"},
                function (data) {
                    info.myCompany=data.data.myCompany;
                    info.lsCompany=data.data.lsCompany;
                    info.countryWarehouse=data.data.countryWarehouse;
                    viewHtml({"info": info, "plan": {}, "detail": {}, "type": 0});
                }
            );
        }
        table.on('edit(LAY-list)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            var warehouse_id=$("#warehouse_id_out").val();
            //编辑sku更新 更新sku相关字段
            if (obj.field == 'sku') {
                obj.data.sku = obj.value.toUpperCase();
                $.ajax({
                    type: 'post',
                    url: '/index/common/getSkuByWarehouse',
                    dataType: 'json',
                    data: {"sku": obj.data.sku,"warehouse_id":warehouse_id},
                    success: function (data) {
                        obj.update(
                            {"sku": "", "sku_name": "", "price": 0, "available_stock": 0}
                        );
                        if (data.code == 1) {
                            obj.data.sku = obj.data.sku;
                            obj.data.sku_name = data.data.sku_name;
                            obj.data.price = data.data.price;
                            obj.data.available_stock = data.data.available_stock;
                            obj.update(
                                obj.data
                            );
                        }
                    }
                })
            } else if (obj.field == 'shop_str') {
                //更改店铺
                var ok = 0;
                obj.update(
                    {"shop_id": 0}
                );
                for (var i  in info.shop) {
                    if (obj.value == info.shop[i]) {
                        obj.data.shop_id = i;
                        obj.update(
                            obj.data
                        );
                        ok = 1;
                    }
                }
                if (ok != 1) {
                    layer.alert('输入错误,店铺:' + obj.value + ' 不存在!');
                }
            } else {
                //重算体积
                obj.data.total_volume = obj.data.unit_volume * obj.data.real_quantity;
                obj.update(
                    obj.data
                );
            }
        });

    })
</script>